/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.nacos.naming.core.v2.service.impl;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.naming.consistency.ephemeral.distro.v2.DistroClientDataProcessor;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.client.Client;
import com.alibaba.nacos.naming.core.v2.client.impl.IpPortBasedClient;
import com.alibaba.nacos.naming.core.v2.client.manager.ClientManager;
import com.alibaba.nacos.naming.core.v2.client.manager.ClientManagerDelegate;
import com.alibaba.nacos.naming.core.v2.event.client.ClientEvent;
import com.alibaba.nacos.naming.core.v2.event.client.ClientOperationEvent;
import com.alibaba.nacos.naming.core.v2.event.metadata.MetadataEvent;
import com.alibaba.nacos.naming.core.v2.index.ClientServiceIndexesManager;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.pojo.BatchInstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.service.ClientOperationService;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.pojo.Subscriber;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 临时注册实例
 * <p>
 * Operation service for ephemeral clients and services.
 *
 * @author xiweng.yy
 */
@Component("ephemeralClientOperationService")
public class EphemeralClientOperationServiceImpl implements ClientOperationService {

    private final ClientManager clientManager;

    public EphemeralClientOperationServiceImpl(ClientManagerDelegate clientManager) {
        this.clientManager = clientManager;
    }

    /**
     * 临时注册实例，默认是 AP 模式，采用 Distro 协议同步给集群中其他 Nacos server
     *
     * @param service  service 根据实例对象属性构建出来的 Service 对象
     * @param instance instance 注册实例
     * @param clientId id of client 生成的注册实例id
     * @throws NacosException
     */
    @Override
    public void registerInstance(Service service, Instance instance, String clientId) throws NacosException {
        // 检查关于keep alive的实例参数
        NamingUtils.checkInstanceIsLegal(instance);

        // 获得单例的 service,如果没有就会注册，底层就是一个 ConcurrentHashMap 来实现缓存的
        Service singleton = ServiceManager.getInstance().getSingleton(service);

        // 临时注册实例校验
        if (! singleton.isEphemeral()) {
            throw new NacosRuntimeException(NacosException.INVALID_PARAM,
                    String.format("Current service %s is persistent service, can't register ephemeral instance.",
                            singleton.getGroupedServiceName()));
        }

        // 根据 clientId 获取 client，并检查 client 是否已经注册过了
        Client client = clientManager.getClient(clientId);
        if (! clientIsLegal(client, clientId)) {
            // 如果已经注册过就直接结束方法
            return;
        }

        // 将注册实例对象里的属性 封装到 nacos 内部实例封装对象中 ，简单理解为两个 VO 的转换
        InstancePublishInfo instanceInfo = getPublishInfo(instance);

        /**
         * 添加 service 和 instance，这里会发布 ClientChangedEvent 事件，非常重要
         * 默认进入 {@link IpPortBasedClient#addServiceInstance(Service, InstancePublishInfo)}
         * 事件异步消费在: {@link DistroClientDataProcessor#syncToAllServer(ClientEvent)}  通过 Distro 协议. 用于将注册实例给同步到其他节点
         */
        client.addServiceInstance(singleton, instanceInfo);


        // 设置最近变更时间
        client.setLastUpdatedTime();
        client.recalculateRevision();

        /**
         *  发布 ClientRegisterServiceEvent 事件
         *  事件异步消费在： {@link ClientServiceIndexesManager#handleClientOperation(ClientOperationEvent)} 用于 service 下的 instance 改变之后，要推送给所有的订阅者
         */
        NotifyCenter.publishEvent(new ClientOperationEvent.ClientRegisterServiceEvent(singleton, clientId));

        /**
         * 发布 InstanceMetadataEvent 事件
         * 事件异步消费在：{@link NamingMetadataManager#onEvent(Event)}  用于实例过期判断，第一次添加的时候不会向缓存中添加任何值,
         * 问题：那这个事件中的 instanceMetadataMap map 中的值是什么时候插入的呢？
         */
        NotifyCenter
                .publishEvent(new MetadataEvent.InstanceMetadataEvent(singleton, instanceInfo.getMetadataId(), false));
    }

    @Override
    public void batchRegisterInstance(Service service, List<Instance> instances, String clientId) {
        Service singleton = ServiceManager.getInstance().getSingleton(service);
        if (! singleton.isEphemeral()) {
            throw new NacosRuntimeException(NacosException.INVALID_PARAM,
                    String.format("Current service %s is persistent service, can't batch register ephemeral instance.",
                            singleton.getGroupedServiceName()));
        }
        Client client = clientManager.getClient(clientId);
        if (! clientIsLegal(client, clientId)) {
            return;
        }
        BatchInstancePublishInfo batchInstancePublishInfo = new BatchInstancePublishInfo();
        List<InstancePublishInfo> resultList = new ArrayList<>();
        for (Instance instance : instances) {
            InstancePublishInfo instanceInfo = getPublishInfo(instance);
            resultList.add(instanceInfo);
        }
        batchInstancePublishInfo.setInstancePublishInfos(resultList);
        client.addServiceInstance(singleton, batchInstancePublishInfo);
        client.setLastUpdatedTime();
        client.recalculateRevision();
        NotifyCenter.publishEvent(new ClientOperationEvent.ClientRegisterServiceEvent(singleton, clientId));
        NotifyCenter.publishEvent(
                new MetadataEvent.InstanceMetadataEvent(singleton, batchInstancePublishInfo.getMetadataId(), false));
    }

    /**
     * 临时实例注销
     *
     * @param service  service
     * @param instance instance
     * @param clientId id of client
     */
    @Override
    public void     deregisterInstance(Service service, Instance instance, String clientId) {
        // 判断 service 是否存在
        if (! ServiceManager.getInstance().containSingleton(service)) {
            Loggers.SRV_LOG.warn("remove instance from non-exist service: {}", service);
            return;
        }
        Service singleton = ServiceManager.getInstance().getSingleton(service);
        Client client = clientManager.getClient(clientId);
        if (! clientIsLegal(client, clientId)) {
            return;
        }

        /**
         *  移除内存中的 instance 对象，这里会发布 ClientChangedEvent 事件，这个很重要
         *  事件消费：{@link DistroClientDataProcessor#onEvent(Event)} 和 注册实例是同一个事件消费者 新增注册实例消费 、移除实例消费  同步到其他节点
         */
        InstancePublishInfo removedInstance = client.removeServiceInstance(singleton);
        client.setLastUpdatedTime();
        client.recalculateRevision();



        if (null != removedInstance) {
            /**
             * 发布 ClientDeregisterServiceEvent 事件
             * 事件消费者： {@link ClientServiceIndexesManager#handleClientOperation(ClientOperationEvent)}  service 下的 instance 改变之后，要推送给所有的订阅者
             */
            NotifyCenter.publishEvent(new ClientOperationEvent.ClientDeregisterServiceEvent(singleton, clientId));


            /**
             * 发布 InstanceMetadataEvent 事件
             */
            NotifyCenter.publishEvent(
                    new MetadataEvent.InstanceMetadataEvent(singleton, removedInstance.getMetadataId(), true));
        }
    }

    /**
     * 添加订阅
     *
     * @param service    监听目标
     * @param subscriber 将订阅者(发起者)信息进行封装，用于  根据 ip 和 port 来进行 udp 推送
     * @param clientId   将订阅者(发起者)的 ip信息 生成的 clientId 保存在缓存 clientManager 中
     */
    @Override
    public void subscribeService(Service service, Subscriber subscriber, String clientId) {
        // 获取监听目标单例的 service
        Service singleton = ServiceManager.getInstance().getSingletonIfExist(service).orElse(service);

        // 判断订阅者(发起者)的 ip信息 生成的 clientId 是否有效
        Client client = clientManager.getClient(clientId);
        if (! clientIsLegal(client, clientId)) {
            return;
        }

        /**
         * client 添加 service 和 subscriber
         */
        client.addServiceSubscriber(singleton, subscriber);

        // 设置更新时间，以防被过期定时任务清理了
        client.setLastUpdatedTime();

        /**
         * 发布 ClientSubscribeServiceEvent
         * 消费者 {@link ClientServiceIndexesManager#handleClientOperation(ClientOperationEvent)} 表示这个 service 变动之后，需要推送给这个 clientId
         *
         */
        NotifyCenter.publishEvent(new ClientOperationEvent.ClientSubscribeServiceEvent(singleton, clientId));
    }

    @Override
    public void unsubscribeService(Service service, Subscriber subscriber, String clientId) {
        Service singleton = ServiceManager.getInstance().getSingletonIfExist(service).orElse(service);
        Client client = clientManager.getClient(clientId);
        if (! clientIsLegal(client, clientId)) {
            return;
        }
        client.removeServiceSubscriber(singleton);
        client.setLastUpdatedTime();
        NotifyCenter.publishEvent(new ClientOperationEvent.ClientUnsubscribeServiceEvent(singleton, clientId));
    }

    private boolean clientIsLegal(Client client, String clientId) {
        if (client == null) {
            Loggers.SRV_LOG.warn("Client connection {} already disconnect", clientId);
            return false;
        }
        if (! client.isEphemeral()) {
            Loggers.SRV_LOG.warn("Client connection {} type is not ephemeral", clientId);
            return false;
        }
        return true;
    }
}
